<template> 
  <el-card class="form-container" shadow="never">
    <el-form
      :model="partner"
      :rules="rules"
      ref="partnerFrom"
      label-width="150px"
      size="small">
      <el-form-item label="公司log：" prop="partnerLog">
        <el-upload
          class="upload-demo"
          action="string"
          :before-upload="beforeAvatarUpload"
          :http-request="beforeUpload"
          :show-file-list="false"  
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <div v-if="this.logAddress !==undefined&&this.logAddress !==''" >
          <img  width="100%" :src="this.logAddress" alt style="width:200px;height:200px" />
        </div>
      </el-form-item>
      <el-form-item label="公司名称：" prop="partnerName">
        <el-input v-model="partner.partnerName" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="管理员账号：">
        <!--<el-select
          v-model="partner.manager"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading">
          <el-option
            v-for="item in options"
            :key="item.userId"
            :label="item.username"
            :value="item.userId">
          </el-option>
        </el-select>-->
        <el-input v-model="partner.username" readonly class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="管理员用户名：">
        <el-input v-model="partner.fullName" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="管理员联系方式：">
        <el-input v-model="partner.mobile" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="营业执照：" prop="businessLicense">
        <el-upload
          v-model="partner.businessLicense"
          class="upload-demo"
          action=""
          :before-upload="beforeAvatarUpload"
          :http-request="beforelicenseUpload"
          :show-file-list="false" 
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <div v-if="this.licenseAddress !==undefined&&this.licenseAddress !==''" >
          <el-image 
            style="width: 200px; height: 200px"
            :src="this.licenseAddress" >
          </el-image>
        </div>
      </el-form-item>
      <!--<el-form-item label="品牌：" prop="branCode">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="partner.brandCodes" >
          <el-checkbox v-for="item in brands" :label="item.brandCode" :key="item.brandCode">{{item.brandName}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>-->
      <el-form-item label="官网链接：" prop="websit">
        <el-input v-model="partner.websit" class="input-width"></el-input>
      </el-form-item>

      <el-form-item label="合作状态：" prop="name">
        <el-radio v-model="partner.partnership" label="共享模式">共享模式</el-radio>
        <el-radio v-model="partner.partnership" label="底价模式">底价模式</el-radio>
      </el-form-item>
     
      <!-- <el-form-item v-show="partner.product===2">
        <el-select
          v-model="selectProduct"
          filterable
          remote
          reserve-keyword
          placeholder="商品名称/商品货号"
          :remote-method="searchProductMethod"
          :loading="selectProductLoading">
          <el-option
            v-for="item in selectProductOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId">
            <span style="float: left">{{ item.productName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.productSn }}</span>
          </el-option>
        </el-select>
        <el-button @click="handleAddProductRelation()">添加</el-button>
        <el-table ref="productRelationTable"
                  :data="coupon.productRelationList"
                  style="width: 100%;margin-top: 20px"
                  border>
          <el-table-column label="商品名称" align="center">
            <template slot-scope="scope">{{scope.row.productName}}</template>
          </el-table-column>
          <el-table-column label="货号" align="center"  width="120" >
            <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button size="mini"
                         type="text"
                         @click="handleDeleteProductRelation(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item> -->
      <el-form-item label="公司简介：">
        <el-input
          class="input-width"
          type="textarea"
          :rows="5"
          placeholder="请输入内容"
          v-model="partner.profile">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('partnerFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('couponFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
  import {fetchSimpleList as fetchProductList} from '@/api/product';
  import {getUserByUsernameFuzzy, generatePartnerAcount} from '@/api/umc'
  import {uploadFile,downloadFile} from '@/api/file'
  import {getUnassignedBrand} from '@/api/brand'
  import {createPartner} from '@/api/partner'
  const defaultpartner = {
    partnerName:'',
    partnerLog:'',
    partnership:'',
    username:'',
    fullName: '',
    mobile: '',
    websit:'',
    // brandCodes:[],
    profile:'',
    product:'',
    businessLicense:''
  
  };
  const defaultTypeOptions = [
    {
      label: '全场赠券',
      value: 0
    },
    {
      label: '会员赠券',
      value: 1
    },
    {
      label: '购物赠券',
      value: 2
    },
    {
      label: '注册赠券',
      value: 3
    }
  ];
  const defaultPlatformOptions = [
    {
      label: '全平台',
      value: 0
    },
    {
      label: '移动平台',
      value: 1
    },
    {
      label: 'PC平台',
      value: 2
    }
  ];
  export default {
    name: 'CouponDetail',
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
        partner: Object.assign({}, defaultpartner),
        typeOptions: Object.assign({}, defaultTypeOptions),
        platformOptions: Object.assign({}, defaultPlatformOptions),
        brands:[],
        checkAll: false,
        rules: {
          partnerName: [
            {required: true, message: '请输入厂商名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          log: [
            {required: true, message: '请上传log', trigger: 'blur'}
          ],
          partnership: [
            {required: true,message: '合作模式必须',trigger: 'blur'}
          ],
          /*manager: [
            {required: true,message: '请选择管理员',trigger: 'blur'}
          ],*/
          websit: [
            {required: false}
          ],
          brandCode: [
            {required: true,message: '需要关联品牌',trigger: 'blur'}
          ],
          profile: [
            {required: true,message: '公司简介必填',trigger: 'blur'}
          ],
          /*businessLicense: [
            {required: true,message: '营业执照',trigger: 'blur'}
          ]*/
        },

        selectProduct:null,
        selectProductLoading: false,
        selectProductOptions:[],
        selectProductCate: null,
        productCateOptions: [],
        dialogVisible:false,
        logAddress:'',
        licenseAddress:'',



        options: [],
        value: [],
        list: [],
        loading: false
      }
    },
    created(){
      // 获取账号
      generatePartnerAcount().then(res => {
        this.partner.username = res.data
      })
      getUnassignedBrand().then(response=>{
        this.brands=response.data;
      })
    },
    mounted() {
      this.list = this.states.map(item => {
        return { value: `value:${item}`, label: `label:${item}` };
      });
    },
    methods:{
      beforeAvatarUpload(file) {
        const isPic = file.type.indexOf('image') >= 0;
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isPic) {
          this.$message.error('资质照片只能为图片格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isPic && isLt2M;
      },
      /*handleCheckAllChange(val) {
        // this.checkedGoods = val ? cityOptions : [];
        if(val==true){
          this.brands.forEach((item) => {
            this.partner.brandCodes.push(item.brandCode);
          })
        }else{
          this.partner.brandCode=[]
        }
        this.isIndeterminate = false;
      },*/

      beforeUpload(param){
         const formData = new FormData()
      formData.append('file', param.file)
      uploadFile(formData).then(response=>{
        this.partner.partnerLog=response.data.fileId
        this.dialogVisible=true;
        this.logAddress = downloadFile(response.data.fileId)
      })
      },

       beforelicenseUpload(param){
         const formData = new FormData()
      formData.append('file', param.file)
      uploadFile(formData).then(response=>{
        this.partner.businessLicense=response.data.fileId
        this.licenseAddress = downloadFile(response.data.fileId)

      })
      },
     remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
            var param ={};
            param.username = query
            getUserByUsernameFuzzy(param).then(response=>{
              this.options=response.data;
            })
          }, 200);
        } else {
          this.options = [];
        }
      },
      
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
             
                createPartner(this.partner).then(response=>{
                  this.$refs[formName].resetFields();
                  this.$message({
                    message: '提交成功',
                    type: 'success',
                    duration:1000
                  });
                  this.$router.back();
                });
              
            });
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      // resetForm(formName) {
      //   this.$refs[formName].resetFields();
      //   this.coupon = Object.assign({},defaultCoupon);
      // },
       searchProductMethod(query){
      //   if (query !== '') {
      //     this.loading = true;
      //     fetchProductList({keyword:query}).then(response=>{
      //       this.loading=false;
      //       let productList = response.data;
      //       this.selectProductOptions = [];
      //       for(let i=0;i<productList.length;i++){
      //         let item = productList[i];
      //         this.selectProductOptions.push({productId:item.id,productName:item.name,productSn:item.productSn});
             }
      //     });
      //   } else {
      //     this.selectProductOptions = [];
      //   }
      // },
      // handleAddProductRelation(){
      //   if(this.selectProduct===null){
      //     this.$message({
      //       message: '请先选择商品',
      //       type: 'warning'
      //     });
      //     return
      //   }
      //   this.coupon.productRelationList.push(this.getProductById(this.selectProduct));
      //   this.selectProduct=null;
      // },
      // handleDeleteProductRelation(index,row){
      //   this.coupon.productRelationList.splice(index,1);
      // },
      // handleAddProductCategoryRelation(){
      //   if(this.selectProductCate===null||this.selectProductCate.length===0){
      //     this.$message({
      //       message: '请先选择商品分类',
      //       type: 'warning'
      //     });
      //     return
      //   }
      //   this.coupon.productCategoryRelationList.push(this.getProductCateByIds(this.selectProductCate));
      //   this.selectProductCate=[];
      // },
      // handleDeleteProductCateRelation(index,row){
      //   this.coupon.productCategoryRelationList.splice(index,1);
      // },
      // getProductById(id){
      //   for(let i=0;i<this.selectProductOptions.length;i++){
      //     if(id===this.selectProductOptions[i].productId){
      //       return this.selectProductOptions[i];
      //     }
      //   }
      //   return null;
      // },
      // getProductCateList() {
      //   fetchListWithChildren().then(response => {
      //     let list = response.data;
      //     this.productCateOptions = [];
      //     for (let i = 0; i < list.length; i++) {
      //       let children = [];
      //       if (list[i].children != null && list[i].children.length > 0) {
      //         for (let j = 0; j < list[i].children.length; j++) {
      //           children.push({label: list[i].children[j].name, value: list[i].children[j].id});
      //         }
      //       }
      //       this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
      //     }
      //   });
      // },
      // getProductCateByIds(ids){
      //   let name;
      //   let parentName;
      //   for (let i = 0; i < this.productCateOptions.length; i++) {
      //     if (this.productCateOptions[i].value === ids[0]) {
      //       parentName = this.productCateOptions[i].label;
      //       for (let j = 0; j < this.productCateOptions[i].children.length; j++) {
      //         if (this.productCateOptions[i].children[j].value === ids[1]) {
      //           name = this.productCateOptions[i].children[j].label;
      //         }
      //       }
      //     }
      //   }
      //   return {productCategoryId: ids[1], productCategoryName: name, parentCategoryName: parentName};
      // }
    }
  }
</script>
<style scoped>
  .input-width {
    width: 60%;
  }
</style>


